﻿//========================================
// All rights reserved (C) 2017-2100
// CLR 版本：	4.0.30319.42000
// 命名空间:	Transport.MainWindow
// 文 件 名：	MainWindow
// 作    者：	WooG
// 联系方式：	wooglle@163.com
// 创建时间：	2017/9/27 14:46:31
//========================================
using Common;
using Common.XmlHandle;
using Microsoft.Win32;
using Network.UpdateData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

namespace Transport
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public string[] arguments = Program.Args;
        private string rootPath = null;
        private string tempPath = null;
        private string fileUser = null;
        private string fileConfig = null;
        private ClassConfig choicedUser = null;
        private ClassConfig config = null;
        private ClassConfig upload = null;
        private Guid guidd;
        private int btnWidth = 160;
        private XmlTransport xmlTransport = null;

        public MainWindow()
        {
            InitializeComponent();
            //this.arguments = new string[] { "F:\\Programming\\CSharp\\SFJDall\\SFJDManagement\\bin\\Debug\\SFJDService.pdb"  };
            //this.arguments = new string[] { @"C:\Users\WOOG\Desktop\新建文件夹\" };

            //rootPath = Environment.CurrentDirectory;

            //获取程序安装路径
            RegistryKey softKey = Registry.CurrentUser.OpenSubKey("SOFTWARE", true).OpenSubKey("SFJDManagement");
            rootPath = softKey.GetValue("RootPath").ToString();
            tempPath = softKey.GetValue("TempPath").ToString();
            //获取当前程序运行路径
            //rootPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            fileUser = rootPath + "\\XmlUsersData.xml";
            fileConfig = rootPath + "\\Config.xml";
            config = new XmlConfig(fileConfig).GetConfig();
            this.Title = "文件传送器";
            this.SizeToContent = SizeToContent.WidthAndHeight;
            this.ResizeMode = ResizeMode.NoResize;
            this.Grid0.HorizontalAlignment = HorizontalAlignment.Center;
            this.Grid0.Margin = new Thickness(5);
            ClassTransportInfo transInfo = new ClassTransportInfo(this.arguments);

            xmlTransport = new XmlTransport(Common.XmlHandle.TransportType.Upload, tempPath);
            guidd = xmlTransport.AddTransport(transInfo);
            ini();

            /*
            //PathHelper pat = new PathHelper(arguments[0]);
            XmlTransport trans = new XmlTransport(TransportType.Upload);
            Guid gui = trans.AddTransport(PathHelper.GetDirectory2Xml(this.arguments));
            Label lab = new Label();
            lab.Content = gui.ToString();
            lab.FontSize = 16;
            lab.HorizontalAlignment = HorizontalAlignment.Center;
            Grid0.Children.Add(lab);
            */
        }

        private void ini()
        {

            List<ClassConfig> users = new XmlUsersData(fileUser).GetUsersOn();
            if (config.UserLicense != 0 & config.UserLicense != (License)((Enum.GetNames(typeof(License))).Length - 1))
            {
                for(License i = config.UserLicense + 1; i < License.Archive; i++)
                {
                    foreach(ClassConfig user in users)
                    {
                        if(user.UserLicense == i)
                        {
                            upload = user;
                            break;
                        }
                    }
                }
                if(upload != null)
                {
                    Button but = this.getUserButton(upload);
                    but.Content = "上传文件至 " + upload.UserName;
                    Grid grid11 = new Grid();
                    grid11.Background = Brushes.LightGray;
                    grid11.Children.Add(but);
                    this.Grid0.Children.Add(grid11);
                }
            }
            Label lab = new Label();
            lab.Content = "发送文件至其他人：";
            lab.FontSize = 16;
            lab.HorizontalAlignment = HorizontalAlignment.Center;
            Grid0.Children.Add(lab);
            WrapPanel grid12 = new WrapPanel();
            grid12.Width = users.Count < 5 ? (btnWidth + 10) : (users.Count / 4 * (btnWidth + 10));
            grid12.HorizontalAlignment = HorizontalAlignment.Center;
            Grid0.Children.Add(grid12);
            foreach(ClassConfig user in users)
            {
                if (user.UserGuid == config.UserGuid)
                    continue;
                if (upload != null && user.UserGuid == upload.UserGuid)
                    continue;
                Button buf = this.getUserButton(user);
                grid12.Children.Add(buf);
            }
        }

        private Button getUserButton(ClassConfig user)
        {
            if(user != null)
            {
                Button btn = new Button();
                btn.Width = btnWidth;
                btn.Height = 50;
                btn.FontSize = 16;
                btn.Content = user.UserName;
                btn.Margin = new Thickness(5);
                Binding btnBind = new Binding();
                btnBind.Source = user;
                btn.SetBinding(Button.DataContextProperty, btnBind);
                btn.Click += Btn_Click;
                return btn;
            }
            else
            {
                return null;
            }
        }

        private void Btn_Click(object sender, RoutedEventArgs e)
        {
            if(sender is Button)
            {
                Button bt = sender as Button;
                Binding bind = BindingOperations.GetBinding(bt, Button.DataContextProperty);
                ClassConfig user = bind.Source as ClassConfig;
                choicedUser = user;
                Packet packet = new Packet(11, config.UserGuid, config.UserGuid, choicedUser.UserGuid.ToString() + '♠' + guidd.ToString());
                SendTcp(packet.ToBytes());
                Close();
            }
        }

        private void SendTcp(byte[] bytes)
        {
            IPAddress myIP = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault<IPAddress>(a => a.AddressFamily.ToString().Equals("InterNetwork"));
            IPEndPoint ipe = new IPEndPoint(myIP, PacketHandle.msgInPort);
            Socket sSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                sSocket.Connect(ipe);
                sSocket.Send(bytes);
                sSocket.Shutdown(SocketShutdown.Both);
                sSocket.Close();
            }
            catch 
            {
                return;
            }
        }
    }
}
